package com.lcq.springbootcreate.project.service;

import com.lcq.springbootcreate.project.ExceptionAndEnum.MallException;
import com.lcq.springbootcreate.project.ExceptionAndEnum.MallExceptionEnum;
import com.lcq.springbootcreate.project.Util.MD5Utils;
import com.lcq.springbootcreate.project.common.Constant;
import com.lcq.springbootcreate.project.dao.UserDao;
import com.lcq.springbootcreate.project.entity.User;
import com.lcq.springbootcreate.project.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class UserService {

    @Autowired
    UserDao userDao;


    public User getUserById(int id) {
        return userDao.getUserById(id);
    }


    public int register(String userName, String passWord) throws MallException {
        User result = userDao.getUserByName(userName);
        if (result != null) {
            throw new MallException(MallExceptionEnum.NAME_EXISTS);
        }
        // 如果遇到主键自动插入的我们应该这么办
        // 如何向数据库插入时间
        User user = new User();
        user.setUsername(userName);
        // 应该对密码进行加密MD5
        try {
            user.setPassword(MD5Utils.getMD5str(passWord+Constant.SALT));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return userDao.insertByUser(user);
    }
    public User login(String userName, String passWord) throws MallException {
        String md5Password = null;
        try {
            md5Password = MD5Utils.getMD5str(passWord+ Constant.SALT);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        User user = userDao.getUserByName(userName);
        if (user.getPassword().equals(md5Password)){
            System.out.println("查询到的sql:"+user.toString());
            return user;
        }else {
            throw new MallException(MallExceptionEnum.WRONG_PASSWORD);
        }
    }

    public void updateSignatureByUser(User user) throws MallException {
        int count =userDao.updateSignatureByUserId(user);
        if (count > 1){
            throw new MallException(MallExceptionEnum.UPDATE_FAILED);
        }
    }
    public boolean checkAdminRole(User user){
        return user.getRole().equals(2);
    }
}
